#!/bin/bash

if [ "$1" = "--help" ]; then
  echo "Please export the following required variables before running this script:"
  echo ""
  echo "CC:                   Set to the target specific compiler command."
  echo "CXX:                  Set to the target specific compiler command."
  echo "CIFX_HOST_MACHINE:    Set to the machine the source should be built 'for'"
  echo "                      e.g. export CIFX_HOST_MACHINE=\$(/bin/bash -c \"\$CC -dumpmachine\")"
  echo "CIFX_BUILD_MACHINE:   Set to the machine the source should be build 'on'"
  echo "                         default: gcc -dumpmachine"
  echo "PATH_TO_LIBPCIACCESS: Set to the path where the libpciaccess is located"
  echo "                      e.g. export PATH_TO_LIBPCIACCESS=/home/project/target/libs/"
  echo "                      NOTE: Set to empty string if libpciaccess is statically linked to libcifx."
  echo "PATH_TO_LIBCIFX:      Set to path where the libcifx is located"
  echo "                         default: set to '../../driver/libcifx/src/.libs/'"
  echo "PATH_TO_INCCIFX:      Set to path where the libcifx is located"
  echo "                         default: set to '../../driver/libcifx/src,../../driver/libcifx/src/Toolkit'"
  echo ""
  echo "NOTE: Multiple (include) paths can be given via comma separated list."
  echo "      For more options run the provided configure script directly."
  exit
fi

if [ -n $1 ]; then
  USER_PARAM=$1
fi

if [ -z $CIFX_HOST_MACHINE ]; then
  echo "Error - aborting build process! Host name not set (configure --host=xxx)!"
  echo "For more information run this script with '--help'."
  exit
fi

if [ -z $CIFX_BUILD_MACHINE ]; then
  CIFX_BUILD_MACHINE=$(/bin/bash -c "gcc -dumpmachine")
fi

if [ -z $PATH_TO_LIBPCIACCESS ]; then
  echo "Error - aborting build process! Path to libpciaccess not specified (PATH_TO_LIBPCIACCESS)!"
  echo "For more information run this script with '--help'."
  exit
fi

if [ -z $PATH_TO_LIBCIFX ]; then
  PATH_TO_LIBCIFX="../../driver/libcifx/src/.libs/"
fi
if [ -z $PATH_TO_INCCIFX ]; then
  PATH_TO_INCCIFX="../../driver/libcifx/src,../../driver/libcifx/src/Toolkit"
fi

OIFS=$IFS;
IFS=",";

#cifx lib
INCCIFX=($PATH_TO_INCCIFX)
for (( i=0; i < ${#INCCIFX[@]} ; i++ )) ;
do
  TMP_CIFX_CFLAGS="${TMP_CIFX_CFLAGS} -I${INCCIFX[$i]}"
done
TMP_CIFX_LIBS="-L${PATH_TO_LIBCIFX}"

#pciaccess lib, in case the library is statically linked to libcifx this is not necessary
TMP_PCIACESS_LIBS="-lpciaccess -L${PATH_TO_LIBPCIACCESS}"

IFS=$OIFS;

./configure --build=${CIFX_BUILD_MACHINE} --host=${CIFX_HOST_MACHINE} $USER_PARAM libcifx_CFLAGS="${TMP_CIFX_CFLAGS}" libcifx_LIBS="${TMP_CIFX_LIBS}" PCIACCESS_CFLAGS="${TMP_PCIACCESS_CFLAGS}" PCIACCESS_LIBS="${TMP_PCIACESS_LIBS}"

